<?php

// ******************************************************************************
//
// split search into several pages
//
// ******************************************************************************
function get_split_search_links($total_results, $results_per_page, $start_index, $item_string) {
	
	$pagecount = ($total_results-1) / $results_per_page;
		
	if ($results_per_page > 1)
		$current_page = intval($start_index / $results_per_page)+1;
	else
		$current_page = intval($start_index / $results_per_page);
	
	if ($pagecount > intval($pagecount))
		$pagecount = intval($pagecount) +1;
	else
		$pagecount = intval($pagecount);
	
  	if ($pagecount > 1) {
		
		if ($current_page > 1) {
				$replace_array['START_INDEX'] = strval((($current_page-2) * $results_per_page));
				$replace_array['PAGE_NUM'] = "<";
				echo replace_placeholders($item_string, $replace_array);
				echo "&nbsp;|&nbsp;";
		}
		
		// echo "Seite ".$current_page." von ".$pagecount;
		
		
		
		
		for ($i=1; $i<=$pagecount; $i++) {
			if ($current_page != $i) {
				$replace_array['START_INDEX'] = strval((($i-1) * $results_per_page));
				$replace_array['PAGE_NUM'] = strval($i);
				// example "<a href=\"javascript:show_search_result('[START_INDEX]')\">[PAGE_NUM]</a>"
				echo replace_placeholders($item_string, $replace_array);
			}
			else {
				echo "<b>".$i."</b>";
			}
			echo "&nbsp;|&nbsp;";
		}
		
		if ($current_page < $pagecount) {
				$replace_array['START_INDEX'] = strval((($current_page) * $results_per_page));
				$replace_array['PAGE_NUM'] = ">";
				// echo "&nbsp;|&nbsp;";
				echo replace_placeholders($item_string, $replace_array);
		}
		
	}

}

// ******************************************************************************
//
// remove the linebreaks from a string, e.g. for use in JavaScript
//
// ******************************************************************************
function strip_line_breaks($text) {
	return preg_replace("/(\r\n|\n|\r)/", "", $text);
}

// ******************************************************************************
//
// get a mysql date from a german date
//
// ******************************************************************************
function get_mysql_date_from_german_date($german_date) {
	$date_array = preg_split('/[. ]/', $german_date);
	if (count($date_array) < 3)
		return NULL;
	else {
		$mytime = strtotime($date_array[2]."-".$date_array[1]."-".$date_array[0]);
		$timearray = get_time_array($mytime);
		if ($mytime == -1)
			return NULL;
			
		return $timearray['tm_year']."-".$timearray['tm_mon']."-".$timearray['tm_mday'];
	}
}

// ******************************************************************************
//
// get a german date from mysql date
//
// ******************************************************************************
function get_german_date_from_mysql_date($mysql_date) {
	
	if (!isset($mysql_date) || $mysql_date == "")
		return NULL;
	
	// check if it's not NULL
	$date_array = preg_split('/[- :]/', $mysql_date);
	if (isset($date_array) && $date_array[0] == "0000")
		return NULL;
	
	$mytime = strtotime($mysql_date);
	if ($mytime == -1)
		return NULL;
	else {
		$time_array = get_time_array($mytime);
		return $time_array['tm_mday'].".".$time_array['tm_mon'].".".$time_array['tm_year'];
	}
}

// ******************************************************************************
//
// get a german date from timestamp
//
// ******************************************************************************
function get_german_date_from_time($mytime) {
	if ($mytime == NULL)
		$mytime = time();
	$time_array = get_time_array($mytime);
	return $time_array['tm_mday'].".".$time_array['tm_mon'].".".$time_array['tm_year'];
}

// ******************************************************************************
//
// validate a german date
//
// ******************************************************************************
function check_german_date($german_date_string) {
	// convert the date to an english format
	$date_string = get_mysql_date_from_german_date($german_date_string);
	
	// get the seconds since 1.1.1970 from english date
	$date = strtotime($date_string);
	
	// check if the results are valid and the original date equals the calculated date
	// (32.3.2003 will be converted to 01.04.2003)
	if ($date == -1 || $date_string == NULL || get_german_date_from_time($date) != $german_date_string) {
		return FALSE;
	}
	return TRUE;
}

// ******************************************************************************
//
// get seconds since 1.1.1970  from german date
//
// ******************************************************************************
function get_time_from_german_date($german_date_string) {
	// convert the date to an english format
	$date_string = get_mysql_date_from_german_date($german_date_string);
	
	// get the seconds since 1.1.1970 from english date
	$time = strtotime($date_string);
	
	return $time;
}

// ******************************************************************************
//
// get a mysql date from time (seconds since 01.01.1970)
//
// ******************************************************************************
function get_mysql_timestamp($time = NULL) {
	if (isset($time))
		return date("Y-m-d H:i:s", $time);
	else
		return date("Y-m-d H:i:s");
}

// ******************************************************************************
//
//get the suffix of a filename
//
// ******************************************************************************

function get_filename_suffix($filename){
	// split the filename by periods
	$filenameparts = split("\.",$filename);
	if (count($filenameparts) < 2)
		return "";
		
	$filename_prefix = $filenameparts[0];
	$filename_suffix = $filenameparts[count($filenameparts)-1];

	return strtolower($filename_suffix);
}

// ******************************************************************************
//
// get the contents of a directory
//
// ******************************************************************************
function get_directory_listing($dirname) {
	
	if (!is_dir($dirname))
		return NULL;
	
	$result_array=array();   
	$handle=opendir($dirname); 
	while ($file = readdir($handle)) { 
		if($file=='.'||$file=='..' || is_dir($dirname.$file) )
			continue;
		else
			$result_array[]=$file; 
	} 
	closedir($handle); 
	return $result_array;
}

// ******************************************************************************
//
// check the syntax of an email address
//
// ******************************************************************************
function validate_email($email_address) { 
	if ($email_address == '')
		return FALSE; 
    if (ereg("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]+\.[a-zA-Z]+$", trim($email_address))) 
		return TRUE; 
    return FALSE; 
} 

// ******************************************************************************
//
// read the contents of a file into a variable
//
// ******************************************************************************
function file2string($filepath) {
	$buffer = "";

    if($file = fopen("$filepath", "r")) {
    	$buffer = fread ($file, filesize ($filepath));
		fclose ($file);
	}
	else {
		do_debug("reading of file ".$filepath." failed",0);
	}
	do_debug("contents of file: ".$buffer,2);
	return $buffer;
}

// ******************************************************************************
//
// replace placeholders with the corresponding value within an associative array
// placeholders are enclosed by brackets: [placeholdername] 
//
// ******************************************************************************
function replace_placeholders($content, $varArray) {
	
	if (count($varArray) > 0) {
	
		foreach($varArray as $key_val => $value) {
			$pattern = "\[\[".$key_val."\]\]";
			$content = ereg_replace($pattern, $value, $content);
		}
	}
	return $content;
}

// ******************************************************************************
//
// display this error in case of an invalid session
//
// ******************************************************************************
function send_invalid_session_info() {
	do_debug ("attempt to access invalid/expired session.", 1);
	send_error_info(2, "Session invalid");
}

// ******************************************************************************
//
// display this error in case of insufficient or wrong request parameters
//
// ******************************************************************************
function send_invalid_parameter_info() {
	do_debug ("missing request parameters.", 1);
	send_error_info(2, "Invalid or missing parameter(s)");
}

// ******************************************************************************
//
// read the contents of a file into a variable
//
// ******************************************************************************
function send_error_info ($returncode, $message) {
	// create an associative array with all the parameters to return to the client
	$returnparams['returncode'] = $returncode;
	$returnparams['message'] = $message;
	output_urlencoded($returnparams);
	exit();
}

// ******************************************************************************
//
// call a URL and send parameters as post variables
// $postvars is an array of values you want to post to the server
//
// ******************************************************************************
function get_post_url ($url, $postvars) {
	$ch = curl_init ($url);
	$querystring = "";
	
	foreach($postvars as $key_val => $value) {
		$value = urlencode($value);
		$querystring .= $querystring.$key_val."=".$value."&";
	}
	
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_POST, 1);
	curl_setopt ($ch, CURLOPT_POSTFIELDS, $querystring);
	curl_setopt ($ch, CURLOPT_HEADER, 0);
	
	do_debug("execute curl call: ".$url, 2);

	$result = curl_exec ($ch);
	
	// do_debug("curl url result: ".$result, 2);
	
	if (curl_error($ch) != "") {
		do_debug("curl error while accessing the URL ". $url .". ID: ".curl_errno($ch)." message: ".curl_error($ch), 0);
	}	
	
	curl_close ($ch);
	
	return $result;
}

// ******************************************************************************
//
// call a URL
//
// ******************************************************************************
function get_url ($url) {
	$ch = curl_init ($url);
	
	foreach($postvars as $key_val => $value) {
		$value = urlencode($value);
	}
	
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_HEADER, 0);
	
	do_debug("execute curl call: ".$url, 2);

	$result = curl_exec ($ch);
	
	// do_debug("curl url result: ".$result, 2);
	
	if (curl_error($ch) != "") {
		do_debug("curl error while accessing the URL ". $url .". ID: ".curl_errno($ch)." message: ".curl_error($ch), 0);
	}	
	
	curl_close ($ch);
	
	return $result;
}

// ******************************************************************************
//
// call a URL and send parameters and files as post variables
// $postvars is an array of data or files you want to post to the server
//
// ******************************************************************************
function get_post_url_multipart ($url, $postvars) {
	$ch = curl_init ($url);
	$querystring = "";
	
	
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_POST, 1);
	curl_setopt ($ch, CURLOPT_POSTFIELDS, $postvars);
	curl_setopt ($ch, CURLOPT_HEADER, 0);
	
	do_debug("execute curl call: ".$url, 2);

	$result = curl_exec ($ch);
	
	// do_debug("curl url result: ".$result, 2);
	
	if (curl_error($ch) != "") {
		do_debug("curl error while accessing the URL ". $url .". ID: ".curl_errno($ch)." message: ".curl_error($ch), 0);
	}	
	
	curl_close ($ch);
	
	return $result;
}


// ******************************************************************************
//
// call a URL and send parameters as post variables
// $postvars is an array of values you want to post to the server
// response data will be ignored
//
// ******************************************************************************
function call_post_url ($url, $postvars) {
	$ch = curl_init ($url);
	$querystring = "";
	
	foreach($postvars as $key_val => $value) {
		$value = urlencode($value);
		$querystring .= $querystring.$key_val."=".$value."&";
	}
	
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0);
	curl_setopt ($ch, CURLOPT_POST, 1);
	curl_setopt ($ch, CURLOPT_POSTFIELDS, $querystring);
	curl_setopt ($ch, CURLOPT_HEADER, 0);
	
	do_debug("execute curl call: ".$url, 2);

	curl_exec ($ch);
	
	if (curl_error($ch) != "") {
		do_debug("curl error while accessing the URL ". $url .". ID: ".curl_errno($ch)." message: ".curl_error($ch), 0);
		return FALSE;
	}	
	
	curl_close ($ch);
	return TRUE;
}

// ******************************************************************************
//
// converts an url-encoded list of key-value-pairs into an associative array
//
// ******************************************************************************
function get_associative_array($paramstring) {
	$array = explode("&",$paramstring);
	$resultArray = NULL;

	for ($i=0; $i < count($array); $i++) {
	
	    $pair = split('=', $array[$i]);
	    if (count($pair) > 1) {	
			$resultArray[urldecode($pair[0])] = urldecode($pair[1]);
		}
	}
	
	return $resultArray;
}


// ******************************************************************************
//
// converts the contents of an assoviative array into an url-encoded String
//
// ******************************************************************************
function create_urlencoded_paramlist($paramarray) {
	$paramstring = "";
	
	foreach($paramarray as $key_val => $value) {
		// $paramstring .= urlencode($key_val) ."=". urlencode($value) ."\n";
		$paramstring .= urlencode($key_val) ."=". urlencode($value) ."&";
	}
	
	$paramstring .= "loaded=true&";
	
	return $paramstring;
}

// ******************************************************************************
//
// output a list of key-value-pairs as url encoded string
//
// ******************************************************************************
function output_urlencoded($paramarray) {
	
	$paramstring="";
	
	if (isset($GLOBALS['CONTENT_TYPE']) )
		header("Content-type: ".$GLOBALS['CONTENT_TYPE']);
	
	if ($paramarray != NULL) {
		$paramstring = create_urlencoded_paramlist($paramarray);
	}
	
	do_flexible_debug($_SERVER['QUERY_STRING'] , 2, $GLOBALS['IO_LOGFILE']);
	do_flexible_debug($paramstring, 2, $GLOBALS['IO_LOGFILE']);
	echo $paramstring;
	return;
}

// ******************************************************************************
//
// log a debug message to the logfile defined in the global variable LOGFILE (config.php)
//
// ******************************************************************************
function do_debug ( $msg, $type ) {
	// parameter type is an integer value.
	// 0 - fatal error should be logged anyway
	// 1 - medium severe error. only log with log level MEDIUM
	// 2 - debug message. only log whith log level HIGH
	
	// currently 3 Log-Levels are implemented:
	// HIGH - all messages will be logged
	// MEDIUM - only messages of types lower than 2 will be logged
	// LOW - only messages of type 0 will be logged
	// NONE - nothing will be logged	 
	if ($GLOBALS['LOGLEVEL'] == "NONE")
		return;	
	
	else if ($GLOBALS['LOGLEVEL'] == "LOW" && $type > 0)
		return;
		
	else if ($GLOBALS['LOGLEVEL'] == "MEDIUM" && $type > 1)
		return;
		
	else
	    error_log ( date ( "Y-m-d H:i:s" ) .  "> $msg\n", 3, $GLOBALS['LOGFILE'] );
}

// ******************************************************************************
//
// log a debug message to the logfile defined in the global variable LOGFILE (config.php)
//
// ******************************************************************************
function do_flexible_debug ( $msg, $type, $file ) {
	// parameter type is an integer value.
	// 0 - fatal error should be logged anyway
	// 1 - medium severe error. only log with log level MEDIUM
	// 2 - debug message. only log whith log level HIGH
	
	// currently 3 Log-Levels are implemented:
	// HIGH - all messages will be logged
	// MEDIUM - only messages of types lower than 2 will be logged
	// LOW - only messages of type 0 will be logged
	// NONE - nothing will be logged	 
	if ($GLOBALS['LOGLEVEL'] == "NONE")
		return;	
	
	else if ($GLOBALS['LOGLEVEL'] == "LOW" && $type > 0)
		return;
		
	else if ($GLOBALS['LOGLEVEL'] == "MEDIUM" && $type > 1)
		return;
		
	else
	    error_log ( date ( "Y-m-d H:i:s" ) .  "> $msg\n", 3, $file );
}

// ******************************************************************************
//
// append to file
//
// ******************************************************************************
function append_to_file ( $msg,$file ) {
    error_log ( $msg, 3, $file );
}

// ******************************************************************************
//
// send a redirect to the specified page
// MS IIS/PWS has a bug in which it does not allow us to send a cookie
// and a redirect in the same HTTP header.
// See the following for more info on the IIS bug:
// http://www.faqts.com/knowledge_base/view.phtml/aid/9316/fid/4
//
// ******************************************************************************
function do_redirect ( $url ) {
    Header ( "Location: $url" );
    echo "<HTML><HEAD><TITLE>Redirect</TITLE><meta http-equiv=\"refresh\" content=\"0; URL=".$url."\"></HEAD><BODY>" .
      "Redirecting to ... <A HREF=\"" . $url . "\">here</A>.</BODY></HTML>.\n";
	exit;
}



// ******************************************************************************
//
// array of prime numbers needed for scramble/descramble
//
// ******************************************************************************
$primenumbers = array(49,37,19,47,23,29,41,31,43,17);

// ******************************************************************************
//
// descrambles a number into a decimal value to hide real values from users
//
// ******************************************************************************
function descrambleNumber($number) {
	
	global $primenumbers;
	
	if(!is_numeric(hexdec($number))) {
		do_debug ("checksum failure. attempt to descramble invalid data.", 0);
		return NULL;
	}
	$primeNumHex = substr($number, strlen($number)-2, 2);
	$primeNumDec = hexdec($primeNumHex)+"";
	if (strlen($primeNumDec) < 2)
		$primeNumDec = "0".$primeNumDec;
		
	$primeIndex1 = substr($primeNumDec,0,1);
	$primeIndex2 = substr($primeNumDec,1,1);
	$numberMultiplied = substr($number, 0,strlen($number)-2);
	
	$result = (hexdec($numberMultiplied))/$primenumbers[$primeIndex1]/$primenumbers[$primeIndex2];
	
	// check for checksum error
	if ( round($result) != $result)
		return NULL;
	
	return $result;
		
}

// ******************************************************************************
//
// scrambles a number into a hexadecimal value to hide real values from users
//
// ******************************************************************************
function scrambleNumber ($number) {
	
	if(!is_numeric($number)) {
		do_debug ("attempt to scramble non-numeric data.", 0);
		return NULL;
	}
		
	global $primenumbers;

	$primeIndex1 = rand(0,9);
	$primeIndex2 = rand(0,9);
	$primeNum1 = $primenumbers[$primeIndex1];
	$primeNum2 = $primenumbers[$primeIndex2];
	$primeNumString = $primeIndex1 . "" . $primeIndex2 . "";
	$primeNumHex = dechex($primeNumString);
	
	if (strlen($primeNumHex) == 1)
		$primeNumHex = "0".$primeNumHex;
		
	return dechex($number*$primeNum1*$primeNum2).$primeNumHex."";

}

// ******************************************************************************
//
// create a select box from an assiciative array
//
// ******************************************************************************
function get_selectbox_from_array($selectbox_name, $selected_option, $empty_option_flag, $option_array) {
	return get_selectbox_from_array_extended($selectbox_name, $selected_option, $empty_option_flag, "", $option_array);
}

// ******************************************************************************
//
// create a select box from an assiciative array
//
// ******************************************************************************
function get_selectbox_from_array_extended($selectbox_name, $selected_option, $empty_option_flag, $empty_option_display, $option_array) {
	$code =  "<select class=\"select\" size=\"1\" name=\"".$selectbox_name."\" class=\"select01\">\n";
	
	if ($empty_option_flag)
		$code .= "	<option value=\"\">".$empty_option_display."</option>\n";
	
	if (count($option_array)>0) {
		foreach($option_array as $key_val => $value) {
				$code .=  "	<option value=\"".$key_val."\"";
				if ($selected_option == $key_val && $selected_option != "")
					$code .= " selected ";
				
				$code .= ">".$value."</option>\n";
		}
	}
	$code .= "</select>";
	
	return $code;
}

// ******************************************************************************
//
// create a select box from an assiciative array
//
// ******************************************************************************
function get_selectbox_from_array_extended_additional_option($selectbox_name, $selected_option, $empty_option_flag, $empty_option_display, $option_array, $additional_option) {
	$code =  "<select size=\"1\" name=\"".$selectbox_name."\" ".$additional_option.">\n";
	
	if ($empty_option_flag)
		$code .=  "	<option value=\"\">".$empty_option_display."</option>\n";
	
	if (count($option_array)>0) {
		foreach($option_array as $key_val => $value) {
				$code .=  "	<option value=\"".$key_val."\"";
				if (isset($selected_option) && $selected_option != "" && $selected_option == $key_val)
					$code .=  " selected ";
				
				$code .=  ">".$value."</option>\n";
		}
	}
	$code .=  "</select>";
	
	return $code;
}


// ******************************************************************************
//
// create a timestamp with current date. format: YYYY/MM/DD - HH:MIN:SEC
//
// ******************************************************************************
function get_current_time_array() {
	return get_time_array();
}

// ******************************************************************************
//
// create a timestamp. format: YYYY/MM/DD - HH:MIN:SEC
//
// ******************************************************************************
function get_time_array($mytime = NULL) {
	
	if ($mytime == NULL)
		$mytime = time();
	
	$current_time = localtime($mytime, TRUE);
	
	$current_time['tm_year'] = 1900+$current_time['tm_year'];
	
	$current_time['tm_mon']=$current_time['tm_mon']+1; 
	if ($current_time['tm_mon'] < 10)
		$current_time['tm_mon'] = "0".$current_time['tm_mon'];
		
	$current_time['tm_mday']=$current_time['tm_mday']; 
	if ($current_time['tm_mday'] < 10)
		$current_time['tm_mday'] = "0".$current_time['tm_mday'];
	
	$current_time['tm_hour']=$current_time['tm_hour']; 
	if ($current_time['tm_hour'] < 10)
		$current_time['tm_hour'] = "0".$current_time['tm_hour'];
	
	$current_time['tm_min']=$current_time['tm_min']; 
	if ($current_time['tm_min'] < 10)
		$current_time['tm_min'] = "0".$current_time['tm_min'];
	
	$current_time['tm_sec']=$current_time['tm_sec']; 
	if ($current_time['tm_sec'] < 10)
		$current_time['tm_sec'] = "0".$current_time['tm_sec'];
	
	return $current_time;
}

// ******************************************************************************
//
// find and replace strings in textfiles
//
// ******************************************************************************
function find_and_replace_in_file($filename, $pattern, $replacement) {

    $filecontents = file_get_contents ($filename);
    $filecontents = str_replace($pattern, $replacement, $filecontents);
    
    $fp = fopen($filename, "w", 0); #open for writing
	fputs($fp, $filecontents); #write all of $product_xml to our opened file
	fclose($fp); #close the file
    
}

// ******************************************************************************
//
// simple mail method
//
// ******************************************************************************
function send_simple_mail($from_address, $from_name, $recipient_address_array, $subject, $body) {
	
	// prepare the mailer object
	$mail = new phpmailer();
	$mail->From = $from_address;
	$mail->FromName = $from_name;
	
	for ($i=0; $i<count($recipient_address_array); $i++) {
		$mail->AddAddress($recipient_address_array[$i]);
	}
	
	$mail->Mailer = $GLOBALS['MAIL_TYPE'];
	
	if (isset($GLOBALS['MAIL_HOST']))
		$mail->Host = $GLOBALS['MAIL_HOST'];
	
	$mail->Body = $body;
	$mail->Subject = $subject;
	
	
	if(!$mail->Send()) {
		do_debug("sending of mail failed : ".$mail->ErrorInfo, 0);
		print ("sending of mail failed");
	}
}


?>
